package com.bpzj.db.mongo.document;

import org.bson.BsonReader;
import org.bson.BsonWriter;
import org.bson.codecs.Codec;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.EncoderContext;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.types.ObjectId;

public class CountryCodec implements Codec<Country> {

    private CodecRegistry codecRegistry;

    public CountryCodec(CodecRegistry codecRegistry) {
      this.codecRegistry = codecRegistry;
    }

    @Override
    public void encode(BsonWriter writer, Country doc, EncoderContext encoderContext) {
      writer.writeStartDocument();
      writer.writeName("_id");
      writer.writeObjectId(new ObjectId(doc.getId()));
      writer.writeName("name");
      writer.writeString(doc.getName());
      writer.writeEndDocument();
    }

    @Override
    public Country decode(BsonReader reader, DecoderContext decoderContext) {
      reader.readStartDocument();
      String id = reader.readObjectId("_id").toString();
      String name = reader.readString("name");
      reader.readEndDocument();

      Country doc = new Country();
      doc.setId(id);
      doc.setName(name);
      return doc;
    }

    @Override
    public Class<Country> getEncoderClass() {
      return Country.class;
    }
  }
